package com.example.hotHub.service.impl;


import com.alibaba.fastjson.JSON;
import com.example.hotHub.model.NormalHotSearch;
import com.example.hotHub.service.ZhihuHotPointService;
import com.example.hotHub.utils.SimpleMap;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ZhihuHotPointServiceImpl implements ZhihuHotPointService {

    @SneakyThrows
    @Override
    public List<NormalHotSearch> getHotPointList() {
        Document document = Jsoup.connect("https://www.zhihu.com/billboard").get();
        Element context = document.getElementById("js-initialData");
        String data = context.data();
        List<SimpleMap> hotList = SimpleMap.parse(data, SimpleMap.class)
                .getMap("initialState")
                .getMap("topstory")
                .getList("hotList", SimpleMap.class);

        List<NormalHotSearch> normalHotSearchList = new ArrayList<>();

        for (SimpleMap element : hotList) {
            String title = element.getMap("target")
                    .getMap("titleArea")
                    .getString("text");

            String url = element.getMap("target")
                    .getMap("link")
                    .getString("url");

            String describe = element.getMap("target")
                    .getMap("excerptArea")
                    .getString("text");

            String hotValueStr = element.getMap("target")
                    .getMap("metricsArea")
                    .getString("text");

            String imageUrl = element.getMap("target")
                    .getMap("imageArea")
                    .getString("url");


            int hotValue = 0;
            for (char c : hotValueStr.toCharArray()) {
                if (c >= '0' && c <= '9') {
                    hotValue *= 10;
                    hotValue += c - '0';
                } else {
                    break;
                }
            }

            NormalHotSearch normalHotSearch = new NormalHotSearch()
                    .setTitle(title)
                    .setUrl(url)
                    .setDescribe(StringUtils.isEmpty(describe) ? title : describe)
                    .setHotValue(hotValue)
                    .setHotValueUnit("万")
                    .setImageUrl(imageUrl);

            normalHotSearchList.add(normalHotSearch);
        }

        normalHotSearchList = normalHotSearchList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

        log.debug("成功爬取知乎热点: {}", normalHotSearchList);

        return normalHotSearchList;
    }
}
